﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

#region Using

using HJ212_Common;
using HJT212_Protocol_DAL.DAO;
using HJT212_Protocol_DAL.Model;
using HJT212_Protocol_Server;
#endregion

namespace HJT212_Protocol_WinServer
{
    public partial class ServerMainForm : Form
    {
        #region 构造函数
        public ServerMainForm()
        {
            InitializeComponent();
        }
        #endregion

        #region 字段属性
        private CommunicationServer ComuSrv = new CommunicationServer();
        log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        #endregion

        #region 事件

        private void btnSrvStart_Click(object sender, EventArgs e)
        {
            Start();
        }

        private void btnSrvStop_Click(object sender, EventArgs e)
        {
            Stop();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                if (ComuSrv != null && ComuSrv.IsRuning)
                {
                    ComuSrv.Stop();
                }
            }
            catch (Exception ex)
            {

                log.Error("关闭出现异常", ex);
            }
            Process.GetCurrentProcess().Kill();
        }

        private void ServerMainForm_Load(object sender, EventArgs e)
        {
            try
            {
                ShowSysMsg("服务正在启动……", 1);
                lstBoxClients.Items.Clear();
                lstBoxHostClients.Items.Clear();
                new Thread(new ParameterizedThreadStart(o => InitDBClients())).Start();
                ComuSrv.showOnline += new CommunicationServer.showOnlineClients(ShowOnlineClients);
                ComuSrv.showTraceMsg += new CommunicationServer.showMsgEventHandler(showTraceMsg);
                //ComuSrv.showHostOnline += new CommunicationServer.showHostOnlineClients(ShowHostOnlineClients);
                ComuSrv.showHostOnlineEndPoints += new CommunicationServer.showHostOnlineEndPointsEventHandler(ShowHostOnlineEndPoints);
                ComuSrv.showHostTraceMsg += new CommunicationServer.showMsgEventHandler(showHostTraceMsg);



            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            try
            {
                this.Hide();
                this.ShowInTaskbar = false;
                e.Cancel = true;

                this.notifyIcon.ShowBalloonTip(30, "注意", "程序最小化至托盘，防止误操作", ToolTipIcon.Info);
            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }

        private void tolBaseConfig_Click(object sender, EventArgs e)
        {
            SysConfigBaseForm form = new SysConfigBaseForm();
            form.mainForm = this;
            form.ShowInTaskbar = false;
            form.ShowDialog();

        }

        private void ServerMainForm_Shown(object sender, EventArgs e)
        {
            try
            {
                //int i = 0;
                ThreadPool.QueueUserWorkItem(new WaitCallback(o => Start()));
            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }


        private void toolMenuShow_Click(object sender, EventArgs e)
        {
            try
            {
                this.Show();
                this.ShowInTaskbar = true;
                this.StartPosition = FormStartPosition.CenterScreen;
            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }

        private void toolMenuHide_Click(object sender, EventArgs e)
        {
            try
            {
                this.Hide();
                this.ShowInTaskbar = false;
            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }

        private void toolMenuExit_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("确认退出吗？", "警告", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {

                    if (ComuSrv != null && ComuSrv.IsRuning)
                    {
                        try
                        {
                            ComuSrv.Stop();
                        }
                        catch (Exception ex)
                        {
                            log.Error("关闭出现异常", ex);
                        }
                    }
                    Process.GetCurrentProcess().Kill();
                }
            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                this.Show();
                this.ShowInTaskbar = true;
                this.StartPosition = FormStartPosition.CenterScreen;
            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }

        private void toolSaveToFile_Click(object sender, EventArgs e)
        {
            try
            {
                RichTextBox txt = (RichTextBox)contextMenuStripLog.SourceControl;

                string filePath = GetSaveFildDialogFile("log_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt");

                if (string.IsNullOrEmpty(filePath)) return;
                int size = 0;
                HJ212_Common.StreamAndBytes.StringToFile(txt.Text, filePath, out size);

            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }

        private void toolClear_Click(object sender, EventArgs e)
        {
            try
            {
                RichTextBox txt = (RichTextBox)contextMenuStripLog.SourceControl;
                txt.Text = "";
            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }

        #endregion

        #region 方法函数

        private void Start()
        {
            try
            {
                string WaitTimeOut = ConfigOprater.GetNodeValue("WaitTimeOut");
                string RetryCount = ConfigOprater.GetNodeValue("RetryCount");
                string LoginTimeOut = ConfigOprater.GetNodeValue("LoginTimeOut");
                ComuSrv.SendTimes = Convert.ToInt32(RetryCount);
                ComuSrv.SendTimeOut = Convert.ToInt32(WaitTimeOut);
                ComuSrv.LoginTimeOut = Convert.ToInt32(LoginTimeOut);
                ComuSrv.Init();
                ComuSrv.Start();
                string msg = "服务已启动";
                ShowSysMsg(msg, 2);
                this.tolStartSrv.Enabled = false;
            }
            catch (Exception ex)
            {
                log.Error("出现异常", ex);
            }

        }


        private void Stop()
        {
            try
            {
                if (ComuSrv != null && ComuSrv.IsRuning)
                {
                    ComuSrv.Stop();
                    string msg = "服务已关闭";
                    ShowSysMsg(msg, 1);
                    this.tolStartSrv.Enabled = true;
                }
            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }

        public void RestartSrv()
        {
            try
            {
                string msg = "服务重启中……";
                ShowSysMsg(msg, 1);
                Stop();
                Start();
            }
            catch (Exception ex)
            {

                log.Error("关闭出现异常", ex);
            }
        }

        /// <summary>
        /// 显示所有在线的客户端
        /// </summary>
        private void ShowOnlineClients(List<ClientModel> LstClients)
        {
            try
            {
                Delegate ddd = new Action<List<ClientModel>>(delegate(List<ClientModel> lstClts)
                {
                    lstBoxClients.Items.Clear();
                    foreach (ClientModel scsServerClient in lstClts)
                    {
                        if (scsServerClient.OnLineState == 2)
                        {
                            ListViewItem lvtm =
                                new ListViewItem(new[]
                                                    {
                                                        scsServerClient.MCNName,
                                                        scsServerClient.MN,
                                                        scsServerClient.PW,
                                                        string.Format("{0}", scsServerClient.OnLineState)
                                                    });
                            lvtm.Font = new Font("宋体", 9, FontStyle.Bold);
                            lvtm.ForeColor = Color.LightGreen;
                            lstBoxClients.Items.Add(lvtm);
                        }
                    }
                    AutoResizeColumnWidth(lstBoxClients);
                });
                this.BeginInvoke(ddd, LstClients);
            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }
        /// <summary>
        /// 显示所有在线的客户端
        /// </summary>
        private void ShowHostOnlineClients(List<HostClientModel> LstHostClients)
        {
            try
            {
                Delegate ddd = new Action<List<HostClientModel>>(
                    delegate(List<HostClientModel> lstClnt)
                    {
                        lstBoxHostClients.Items.Clear();

                        foreach (HostClientModel HostClient in lstClnt)
                        {
                            if (HostClient.OnLineState == 2)
                            {
                                ListViewItem lvtm = new ListViewItem(new[]
                                                                         {
                                                                             HostClient.MCNName,
                                                                             HostClient.MN,
                                                                             HostClient.PW,
                                                                             string.Format("{0}", HostClient.OnLineState)
                                                                         });
                                lvtm.Font = new Font("宋体", 9, FontStyle.Bold);
                                lvtm.ForeColor = Color.LightGreen;
                                lstBoxHostClients.Items.Add(lvtm);
                            }
                        }
                        AutoResizeColumnWidth(lstBoxHostClients);
                    });
                this.BeginInvoke(ddd, LstHostClients);
            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }

        /// <summary>
        /// 显示所有在线的客户端
        /// </summary>
        private void ShowHostOnlineEndPoints(List<string> LstHostClientendPoints)
        {
            try
            {
                Delegate ddd = new Action<List<string>>(
                    delegate(List<string> lstClnt)
                    {
                        lstBoxHostClients.Items.Clear();

                        foreach (string HostClient in lstClnt)
                        {

                            ListViewItem lvtm = new ListViewItem(new[]
                                                                         {
                                                                             "先河环保上位机",
                                                                             HostClient
                                                                         });
                            lvtm.Font = new Font("宋体", 9, FontStyle.Bold);
                            lvtm.ForeColor = Color.LightGreen;
                            lstBoxHostClients.Items.Add(lvtm);
                        }
                        AutoResizeColumnWidth(lstBoxHostClients);
                    });
                this.BeginInvoke(ddd, LstHostClientendPoints);
            }
            catch (Exception ex)
            {

                log.Error("出现异常", ex);
            }
        }

        private void showTraceMsg(string msg)
        {
            ShowMsg(msg, 2);
               
        }
        private void showHostTraceMsg(string msg)
        {
            ShowHostMsg(msg, 2);
        }

        /// <summary>
        /// 以不同状态显示数据
        /// </summary>
        /// <param name="msg">显示的数据</param>
        /// <param name="type">状态表示，2 黑色 否则红色</param>
        private void ShowMsg(string msg, int type)
        {
            Delegate ddd = new Action<string>(delegate(string str)
            {
                log.Info(str);
                if (this.txtBoxContent.TextLength > 20480)
                {
                    this.txtBoxContent.Clear();
                }
                str = "[" + DateTime.Now.ToString("HH:mm:ss:fff") + "]" + str + "\n";
                this.txtBoxContent.AppendText(str);
                txtBoxContent.Select(Math.Max(0, this.txtBoxContent.Text.Length - str.Length), str.Length);
                txtBoxContent.SelectionColor = type == 2 ? Color.Black : Color.Red;
                txtBoxContent.ScrollToCaret();
            });
            this.BeginInvoke(ddd, msg);
        }

        /// <summary>
        /// 以不同状态显示数据
        /// </summary>
        /// <param name="msg">显示的数据</param>
        /// <param name="type">状态表示，2 黑色 否则红色</param>
        private void ShowSysMsg(string msg, int type)
        {
            Delegate ddd = new Action<string>(delegate(string str)
            {
                log.Info(str);
                this.tolTxtInfo.Text = str;
                this.tolTxtInfo.ForeColor = type == 2 ? Color.Green : Color.Red;
            });
            this.BeginInvoke(ddd, msg);
        }

        /// <summary>
        /// 以不同状态显示数据
        /// </summary>
        /// <param name="msg">显示的数据</param>
        /// <param name="type">状态表示，2 黑色 否则红色</param>
        private void ShowHostMsg(string msg, int type)
        {
            Delegate ddd = new Action<string>(delegate(string str)
            {
                if (this.txtHostContent.TextLength > 20480)
                {
                    this.txtHostContent.Clear();
                }
                log.Info(str);
                str = "[" + DateTime.Now.ToString("HH:mm:ss:fff") + "]" + str + "\n";
                this.txtHostContent.AppendText(str);
                txtHostContent.Select(Math.Max(0, this.txtHostContent.Text.Length - str.Length), str.Length);
                txtHostContent.SelectionColor = type == 2 ? Color.Black : Color.Red;
                txtHostContent.ScrollToCaret();
            });
            this.BeginInvoke(ddd, msg);
        }

        /// <summary>
        /// 加载数据库中配置的客户端列表
        /// </summary>
        private void InitDBClients()
        {
            try
            {

                ClientDao clntdao = new ClientDao();
                ComuSrv.LstClients = clntdao.GetDbClientList();
                HostClientDao Hclntdao = new HostClientDao();
                ComuSrv.LstHostClients = Hclntdao.GetDbClientList();
            }
            catch (Exception ex)
            {
                log.Error("出现异常", ex);
            }
        }

        /// <summary>
        /// 自动根据内容调整列宽
        /// </summary>
        /// <param name="lv"></param>
        private void AutoResizeColumnWidth(ListView lv)
        {
            int count = lv.Columns.Count;
            int MaxWidth = 0;
            Graphics graphics = lv.CreateGraphics();
            Font font = lv.Font;
            ListView.ListViewItemCollection items = lv.Items;

            string str;
            int width;

            lv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

            for (int i = 0; i < count; i++)
            {
                str = lv.Columns[i].Text;
                MaxWidth = lv.Columns[i].Width;

                foreach (ListViewItem item in items)
                {
                    str = item.SubItems[i].Text;
                    width = (int)graphics.MeasureString(str, font).Width;
                    if (width > MaxWidth)
                    {
                        MaxWidth = width;
                    }
                }
                if (i == 0)
                {
                    lv.Columns[i].Width = lv.SmallImageList.ImageSize.Width + MaxWidth;
                }
                lv.Columns[i].Width = MaxWidth;
            }
        }

        public static string GetSaveFildDialogFile(string DefaultFileName)
        {
            string file = "";
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.FileName = DefaultFileName;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //获得文件路径
                file = saveFileDialog1.FileName.ToString();
            }
            return file;

        }
        #endregion







    }
}
